import threading
import tkinter
import traceback
from time import sleep
from pywxdump import read_info
import os
from openai import OpenAI

def main():
    from gui.gui import Gui

    gui = Gui()
    gui_thread = threading.Thread(target=gui.run_gui)
    gui_thread.start()

    info = ""
    while True:
        try:
            info = read_info(None, is_logging=True)
        except:
            traceback.print_exc()
        # 如果解密失败，读取到报错信息
        if isinstance(info, str):
            gui.waiting_label.config(text="请启动微信....")
            sleep(0.5)
        elif isinstance(info, list) and info[0].get("key") == "None":
            gui.waiting_label.config(text="请登陆微信....")
            sleep(0.5)
        else:
            break

    gui.wechat_logged_in(info[0])
    # 这里不再自动调用AI总结，AI调用应在导出成功后由GUI触发

def get_latest_export_html():
    output_dir = "output"
    subdirs = [os.path.join(output_dir, d) for d in os.listdir(output_dir) if os.path.isdir(os.path.join(output_dir, d))]
    if not subdirs:
        raise FileNotFoundError("没有找到任何导出目录")
    latest_dir = max(subdirs, key=os.path.getmtime)
    html_path = os.path.join(latest_dir, "index.html")
    if not os.path.exists(html_path):
        raise FileNotFoundError(f"{html_path} 不存在")
    return html_path

def call_ali_ai_summary(html_path, user_prompt):
    api_key = "sk-1079f46f16cb42088c2e58486c403b2f"
    with open(html_path, "r", encoding="utf-8") as f:
        html_content = f.read()

    final_prompt = user_prompt + "\n\n" + html_content

    client = OpenAI(
        api_key=api_key,
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    )

    completion = client.chat.completions.create(
        model="qwen-plus",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": final_prompt},
        ],
    )
    return completion.choices[0].message.content

if __name__ == "__main__":
    main()
